import {Component, ViewContainerRef, ComponentFactoryResolver, ViewChild, Type, Input} from '@angular/core';
import {NavParams, ViewController} from 'ionic-angular';
import {EmojiRichProvider} from "../emoji/emoji";
import {TextComponent} from "../text/text";
import {isUndefined} from "ionic-angular/util/util";


export abstract class IRichTextProvider {
  resolve<T>(str: string): Type<T>
  {
    return null;
  }
}

/*
  Generated class for the RichTextViewer page.

  See http://ionicframework.com/docs/v2/components/#navigation for more info on
  Ionic pages and navigation.
*/
@Component({
  selector: 'rich-text-viewer',
  templateUrl: 'rich-text-viewer.html'
})
export class RichTextViewer {
  private _rawText: string = '';

  providers: Array<Type<IRichTextProvider>> = [EmojiRichProvider];

  @Input()
  get rawText(): string {
    return this._rawText;
  }
  set rawText(v: string) {
    this._rawText = v;
    this.parse();
  }

  @ViewChild('parent', {read: ViewContainerRef})
  element: ViewContainerRef;

  constructor(public viewCtrl: ViewController, public navParams: NavParams, private viewContainerRef: ViewContainerRef, private resolver: ComponentFactoryResolver) {
    this.providers.push()
  }

  create<T>(type: Type<T>, inputData: Map<string, string> = new Map())
  {
    let ele = this.element.createComponent(this.resolver.resolveComponentFactory(type));
    inputData.forEach((v, k) => {
      ele.instance[k] = v;
    })
  }

  private parse()
  {
    let mark_regexp = new RegExp(/\[([a-zA-Z0-9.\-_\ ]+)\]/);
    let is_text: boolean = false;
    let text_segments = this._rawText.split(mark_regexp);
    text_segments.map(value => {
      is_text = !is_text;
      if (is_text)
      {
        this.create(TextComponent, new Map([['text', value]]));
      }
      else
      {
        this.providers.map(P => {
          let obj_p = new P();
          let mark_param_pair = value.split('-');
          let mark = mark_param_pair[0];
          let param = mark_param_pair.slice(1).join('-');
          let resolved = obj_p.resolve(mark);
          if (resolved !== null) this.create(resolved, new Map([['name', param]]));
        })
      }
    })

  }
}
